/**
 * UserSDK
 *
 * @param {Object} global
 */
using(['utils/fetchEnhancer',
    'utils/Cookie',
    'utils/Storage',
    'utils/helpers'
], function(fetch, Cookie, Storage, helpers){

var global = window;

// 主程序
var SDK = function() {
    this.doc = document;

    this.notLoginHtml = '<a class="x-nav-item" href="/register">注册</a>' +
        '<a class="x-nav-item" href="/login">登录</a>';
    this.loginHtml = '<a class="x-nav-item x-nav-user-avatar" href="/home/{uid}">' +
            '<img src="{avatar}">' +
        '</a>' +
        '<div class="x-nav-drop">' +
            '<a class="x-nav-drop-item" href="/home/{uid}">' +
                '<span class="x-nav-drop-item-side"><i class="x-icon-home"></i></span>' +
                '<span>个人主页</span>' +
            '</a>' +
            '<a class="x-nav-drop-item" href="/write">' +
                '<span class="x-nav-drop-item-side"><i class="x-icon-write"></i></span>' +
                '<span>投个稿子</span>' +
            '</a>' +
            '<a class="x-nav-drop-item" href="/ucenter">' +
                '<span class="x-nav-drop-item-side"><i class="x-icon-user"></i></span>' +
                '<span>用户中心</span>' +
            '</a>' +
            '<a class="x-nav-drop-item" href="/logout">' +
                '<span class="x-nav-drop-item-side"><i class="x-icon-quit"></i></span>' +
                '<span>退出</span>' +
            '</a>' +
        '</div>';
};
SDK.prototype = {
    constructor: SDK,
    apiRegister: function(data /* nick, password, email, verifyCode */, callback) {
        var ret = 'nick=' + encodeURIComponent(data.nick)
            + '&password=' + encodeURIComponent(data.password)
            + '&email=' + encodeURIComponent(data.email)
            + '&verify_code=' + encodeURIComponent(data.verifyCode);

        fetch('/api/account/register', {
            method: 'POST',
            body: ret

        }).then(function(data) {
            callback(data);
        });
    },
    apiLogin: function(data /* account, password, isEmail */, callback) {
        var ret = 'account=' + encodeURIComponent(data.account)
            + '&password=' + encodeURIComponent(data.password)
            + '&verify_code=' + (data.verifyCode
                ? encodeURIComponent(data.verifyCode)
                : '')
            + '&is_email=' + data.isEmail;

        fetch('/api/account/login', {
            method: 'POST',
            body: ret

        }).then(function(data){
            if(100010 === data.status) {
                XUI.toast.error('账号被封禁');
            }
            callback(data);
        });
    },

    getUid: function() {
        var c = new Cookie();
        return c.getCookie(Fate.COOKIE_PREFIX + 'uid');
    },
    getStrUid: function() {
        var c = new Cookie();
        return c.getCookie(Fate.COOKIE_PREFIX + 'str_uid');
    },
    isLogin: function() {
        var uid = this.getUid();

        if('' !== uid) {
            return true;
        }

        return false;
    },
    getUserInfo: function(callback) {
        if(!this.isLogin()) {
            callback({
                isLogin: false,
                str_uid: '',
                gender: -1,
                userName: '',
                avatar: Fate.STATIC + '/pc/images/avatar.jpg',
                status: 0
            });
            return;
        }

        // 有无缓存
        var storage = new Storage();
        var cache = storage.get('logininfo');
        if(null !== cache) {
            var json = JSON.parse(cache);

            callback({
                isLogin: true,
                str_uid: json.str_uid,
                gender: json.gender,
                userName: json.user_name,
                avatar: json.avatar,
                status: json.status
            });

            return;
        }

        fetch('/api/account/getloginuser', {
            method: 'GET'
        }).then(function(json){
            if(0 === json.status) {
                // one hour
                storage.set('logininfo', JSON.stringify(json.data.data), new Date().getTime() + 3600 * 1000);

                callback({
                    isLogin: true,
                    str_uid: json.data.data.str_uid,
                    gender: json.data.data.gender,
                    userName: json.data.data.user_name,
                    avatar: json.data.data.avatar,
                    status: json.data.data.status
                });
            }
        })
    },
    deleteCache: function() {
        global.localStorage.removeItem('logininfo');
    },

    /* 初始化用户导航 */
    initNav: function(id) {
        var _self = this;
        var wrapper = this.doc.getElementById(id);

        if(this.isLogin()) {
            this.getUserInfo(function(rs){
                var html = _self.loginHtml;
                var avatar = helpers.getAvatar(rs.avatar);
                html = html.replace('{uid}', rs.str_uid).replace('{uid}', rs.str_uid);
                html = html.replace('{avatar}', avatar);

                wrapper.innerHTML = html;
            });

            return;
        }

        // 无登录 删除缓存
        this.deleteCache();
        wrapper.innerHTML = this.notLoginHtml;
    }
};
SDK._instance = null;
SDK.getInstance = function() {
    if(null === SDK._instance) {
        SDK._instance = new SDK();
    }

    return SDK._instance;
};

// export
global.USER_SDK = SDK;

});


// sdk enhancer
using(['components/FramePassport/FramePassport'], function(FramePassport){

var SDK = window.USER_SDK;
SDK.prototype.showLogin = function() {
    FramePassport.getInstance().render('login');
};
SDK.prototype.showRegister = function() {
    FramePassport.getInstance().render('register');
};
SDK.prototype.close = function() {
    FramePassport.getInstance().remove();
};
SDK.prototype.frameLoginSuccess = function() {}

});
